package com.mall.order.biz.handler;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.mall.order.biz.context.CancelOrderContext_X;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author XuBang
 * @TODO:
 * （1）从订单表tb_order中删除一个对应的订单id     or    根据订单id，将订单表tb_order中的status改为“5交易关闭”(采取后者)
 * （2）根据订单id，将订单商品关联表tb_order_item中的一些列的商品的status改为“2库存已释放”
 * @date 2021/11/2$
 * @trainOfthought:
 * 1.注入数据库表格对应的mapper，干活
 * 2.CRUD
 */
@Slf4j
@Component
public class UpdateOrderInfHandler extends AbstractTransHandler{

    //1.注入数据库对应的mapper
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        //2.对实现方法中的context进行向下转型，获取存在真实需要数据的context
        CancelOrderContext_X cancelOrderContext_x = new CancelOrderContext_X();   //context提供基本查询数据
        Order order = new Order();     //提供订单详情对象
        OrderItem orderItem = new OrderItem();   //提供订单商品关联表对象

        //3.根据context中的数据，借助mapper，结合具体的业务逻辑；进行CRUD
        //- 根据订单id，将订单表tb_order中的status改为“5交易关闭”(采取后者)
        order.setOrderId(cancelOrderContext_x.getOrderId());
        order.setUpdateTime(new Date());
        order.setStatus(5);
        orderMapper.updateByPrimaryKeySelective(order);   //只是更新新的model中不为空的字段

        //根据订单id，将订单商品关联表tb_order_item中的一些列的商品的status改为“2库存已释放”
        orderItem.setOrderId(cancelOrderContext_x.getOrderId());
        orderItem.setStatus(2);

        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId",cancelOrderContext_x.getOrderId());

        orderItemMapper.updateByExampleSelective(orderItem,example);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        cancelOrderContext_x.setOrderItems(orderItems);
        return true;
    }
}
